package com.yuan.yblog.portal.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuan.yblog.common.exception.Asserts;
import com.yuan.yblog.common.service.EntityCacheService;
import com.yuan.yblog.crud.entity.Category;
import com.yuan.yblog.crud.entity.User;
import com.yuan.yblog.crud.service.ICategoryService;
import com.yuan.yblog.crud.service.IPostService;
import com.yuan.yblog.crud.service.IUserService;
import com.yuan.yblog.portal.dao.mapper.PostDao;
import com.yuan.yblog.portal.pojo.VO.PostItemVO;
import com.yuan.yblog.portal.pojo.VO.PostVO;
import com.yuan.yblog.portal.pojo.contants.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.yuan.yblog.crud.entity.Post;

/**
* @author 13527
* @description 针对表【post】的数据库操作Service实现
* @createDate 2023-12-03 14:18:01
*/
@Service
public class PostService {

    @Autowired
    PostDao postDao;

    @Autowired
    IUserService iUserService;

    @Autowired
    IPostService iPostService;

    @Autowired
    ICategoryService iCategoryService;

    @Autowired
    AuthenticationService authenticationService;

    @Autowired
    private EntityCacheService entityCacheService;

    @Autowired
    WeekRankService weekRankService;

    /**
     * 多条件文章列表查询
     * @param level 置顶等级，0是最高级
     * @param userId 作者id
     * @param categoryId 分类id
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param sortKey 排序字段
     * @param isDesc 是否降序
     */
    public IPage<PostItemVO> postItemList(Long level, Long userId, Long categoryId, Long pageNumber, Long pageSize, String sortKey, Boolean isDesc) {
        if(categoryId == null || categoryId <= 0) {
            // 分类无效
            categoryId = null;
        }
        if (level == null || level != 0) {
            // 本方法只能查询最高置顶等级
            level = null;
        }
        // 查询文章
        List<Post> postList = postDao.postItemList(level, userId, categoryId, (pageNumber-1)*pageSize, pageSize, sortKey, isDesc);
        Long total = postDao.postItemListCount(level, userId, categoryId);
        // 针对文章查询其类型及其作者信息
        List<PostItemVO> records = new ArrayList<>();
        for (Post post : postList) {
            User user = iUserService.selectByIdAndBuildCache(post.getUserId());
            Category category = iCategoryService.selectByIdAndBuildCache(post.getCategoryId());
            records.add(PostItemVO.of(post, user, category));
        }
        // 封装返回
        IPage<PostItemVO> result = new Page<>(pageNumber, pageSize, total);
        result.setRecords(records);
        return result;
    }

    /**
     * 用户发布新文章，插入新文章
     */
    public Long insertPost(PostVO postVO) {
        // 获取当前登录用户
        User currentUser = authenticationService.getLoginUser();
        // 设置作者id
        postVO.setUserId(currentUser.getId());
        // 转化
        Post post = postVO.toInsertEntity();
        // 插入
        boolean succeed = iPostService.insert(post);
        if(succeed) {
            // 更新用户文章数
            User user = iUserService.selectByIdAndBuildCache(post.getUserId());
            user.setPostCount(user.getPostCount() + 1);
            iUserService.updateAndDeleteCache(user);
            // 插入周榜
            weekRankService.insertPost(post);
            return post.getId();
        }
        return null;
    }

    /**
     * 用户编辑旧文章
     */
    public Long updatePost(PostVO postVO) {
        User currentUser = authenticationService.getLoginUser();
        Post postFromData = iPostService.selectByIdAndBuildCache(postVO.getId());
        if(postFromData == null) {
            Asserts.fail("文章不存在");
        }
        if(!currentUser.getId().equals(postFromData.getUserId())) {
            Asserts.fail("非法操作：当前用户id与文章作者id不匹配");
        }
        // 更新
        Post update = postVO.toUpdateEntity();
        boolean success = iPostService.updateAndDeleteCache(update);
        if (success) {
            // 周榜：先删除，后重新插入
            weekRankService.deletePost(update.getId());
            weekRankService.insertPost(update);
            return 1L;
        }
        return 0L;
    }

    /**
     * 用户删除文章-逻辑删除
     * @param postId 文章id
     */
    public Boolean deletePost(Long postId) {
        User currentUser = authenticationService.getLoginUser();

        Post post = iPostService.selectByIdAndBuildCache(postId);
        if(post == null) {
            //文章不存在
            return false;
        }
        if(!currentUser.getId().equals(post.getUserId())) {
            Asserts.fail("非法操作：当前用户id与文章作者id不匹配");
        }
        // 删除缓存
        entityCacheService.deleteEntity(IPostService.POST, postId);

        // 逻辑删除
        post.setStatus(Status.invalid);
        boolean success = iPostService.updateAndDeleteCache(post);
        if (success) {
            // 更新用户文章数
            User user = iUserService.selectByIdAndBuildCache(post.getUserId());
            user.setPostCount(user.getPostCount() - 1);
            iUserService.updateAndDeleteCache(user);
            // 删除周榜
            weekRankService.deletePost(postId);
        }

        return success;
    }

    /**
     * 根据地查询文章
     * @param id 文章id
     */
    public Post selectByIdAndBuildCache(Long id){
        return iPostService.selectByIdAndBuildCache(id);
    }

}




